package smodul

import (
	"WeChatMGRA/modul"
	"WeChatMGRA/requests"
	"encoding/xml"
	"strings"
	"time"

	"gitee.com/yutiandou/wdtools/wdlog"
	"gitee.com/yutiandou/wdtools/wdutil"
)

var jiangge time.Duration = 300

type VoiceMsg struct {
	XMLName      xml.Name `xml:"voicemsg"`
	Endflag      string   `xml:"endflag,attr"`
	Length       int      `xml:"length,attr"`
	Voicelength  int      `xml:"voicelength,attr"`
	Clientmsgid  string   `xml:"clientmsgid,attr"`
	Fromusername string   `xml:"fromusername,attr"`
	Downcount    int      `xml:"downcount,attr"`
	Cancelflag   int      `xml:"cancelflag,attr"`
	Voiceformat  int      `xml:"voiceformat,attr"`
	Forwardflag  int      `xml:"forwardflag,attr"`
	Bufid        string   `xml:"bufid,attr"`
}

//ReceiveTypeMsg 接受到信息类型为消息
func (r *Robots) ReceiveTypeMsg(data *modul.ReceiveData) {
	//if atomic.LoadInt32(&(r.MaxMsgList)) > conf.Global_Conf.MaxReceiveMsgCount{
	//	return
	//}else{
	//	r.MaxMsgList = atomic.AddInt32(&(r.MaxMsgList),1)
	//	defer func(){
	//		r.MaxMsgList = atomic.AddInt32(&(r.MaxMsgList),-1)
	//	}()
	//}
	//wdlog.Warning("接受到一条消息：",data.Type,";",data.Content)

	switch data.Type {
	case 0: //文字
		plen := len(data.PushContent)
		if plen > 19 {
			if data.PushContent[(plen-19):] == "在群聊中@了你" {
				TextVerify(r, data)
				return
			}
		}
		if !authentication(r, data) {
			return
		}
		switch r.WorkProgress {
		case 100:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendText(r.Wid, wcid, data.Content, false)
				if wdlog.Error(err) {
					return false
				}
				return true
			})
		case 200:
			if !AddMsgToMysql(uint32(r.ID), uint32(r.Broadcasst.ID), 1, data.Content, 0) {
			}
		default:
		}

	case 1: //图片
		if !authentication(r, data) {
			return
		}
		switch r.WorkProgress {
		case 100:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendImage(r.Wid, wcid, data.Content)
				if wdlog.Error(err) {
					return false
				}
				return true
			})
		case 200:
			if !AddMsgToMysql(uint32(r.ID), uint32(r.Broadcasst.ID), 2, data.Content, 0) {
			}
		}

	case 2: //视频
		if !authentication(r, data) {
			return
		}
		//leng := wdutil.RegexpFromStringS(data.Content,` thumbpath="(?s:(.*?))" `,1)
		//if len(leng) <1 {
		//	return
		//}
		//下载视频
		mvurl := requests.DownMV(r.Wid, data.Content, data.MsgId)
		if mvurl == "null" {
			return
		}
		//转发视频
		switch r.WorkProgress {
		case 100:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendMV(r.Wid, wcid, data.Content)
				if wdlog.Error(err) {

					return false

				}
				return true
			})
		case 200:
			if !AddMsgToMysql(uint32(r.ID), uint32(r.Broadcasst.ID), 3, data.Content, 0) {
			}
		}

	case 3: //语音
		if !authentication(r, data) {
			return
		}
		//leng := wdutil.RegexpFromStringS(data.Content,` length="(?s:(.*?))" `,1)
		//if len(leng) <1 {
		//	wdlog.Debugln("语音消息:","消息正则匹配失败")
		//	return
		//}
		vmsg := new(VoiceMsg)
		err := xml.Unmarshal([]byte(data.Content)[5:], vmsg)
		//msglen,err:= strconv.ParseInt(leng[0][1],10,64)
		if wdlog.Error(err) {
			return
		}
		viourl := requests.DownVoice(r.Wid, data.MsgId, int64(vmsg.Length))
		if viourl == "null" {
			wdlog.Debugln("语音消息:", "语音下载url为空")
			return
		}
		switch r.WorkProgress {
		case 100:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendVoice(r.Wid, wcid, viourl, vmsg.Voicelength)
				if wdlog.Error(err) {

					return false

				}
				return true
			})
		case 200:
			if !AddMsgToMysql(uint32(r.ID), uint32(r.Broadcasst.ID), 4, viourl, vmsg.Voicelength) {
			}
		}
	default:
		wdlog.Debugln("接受到一条其他类型信息:", data.Type)
	}
}

func (r *Robots) ReceiveTypeFour(data *modul.ReceiveData) {
	switch data.MsgType {
	case 10000:
		//wdlog.Warning("接受到一条群邀请或踢群消息")
		if strings.Count(data.Content, "邀请你加入了群聊") > 0 {
			if strings.Count(data.Content, "着调生活机器人") > 0 {
				requests.SendText(r.Wid, data.FromUser, "请勿重复添加机器人", false)
				requests.QuitGroup(r.Wid, data.FromUser)
				return
			}
			switch r.AddWorkGroup(data.FromUser) {
			case 2:
				requests.SendText(r.Wid, data.FromUser, "已为本群开启转播服务", false)
			case 3:
				requests.SendText(r.Wid, data.FromUser, "转播群数已达上限，无法提供转播功能，请使用其他机器人", false)
				requests.QuitGroup(r.Wid, data.FromUser)
			case 4:
				requests.SendText(r.Wid, data.FromUser, "群成员信息加载失败，请发送'重新加载'，再次加载本群信息", false)
			case 5:
				requests.SendText(r.Wid, data.FromUser, "请勿重复添加机器人", false)
				requests.QuitGroup(r.Wid, data.FromUser)
			}
		} else if strings.Count(data.Content, "移出群聊") > 0 {
			r.RemoveWorlGroup(data.FromUser)
		}
	default:
	}
}

//authentication 过身份鉴权
func authentication(r *Robots, data *modul.ReceiveData) bool {
	if r.CurrentGroup != data.FromGroup {
		switch r.AddWorkGroup(data.FromGroup) {
		case 2:
			requests.SendText(r.Wid, data.FromGroup, "已为本群开启转播服务", false)
		case 3:
			requests.SendText(r.Wid, data.FromGroup, "转播群数已达上限，无法提供转播功能，请联系客服续费", false)
			requests.QuitGroup(r.Wid, data.FromGroup)
		}
	}
	if _, ok := r.CurrentListWcid.Load(data.FromUser); r.WorkStat == 2 && !ok {
		wdlog.Debugln("语音消息:", "消息不符合主播身份")
		return false
	} else if r.CurrentGroup != data.FromGroup {
		return false
	}
	if r.WorkProgress != 100 && r.WorkProgress != 200 {
		return false
	}
	r.UpdataRobot_Config()
	return true
}

//TextVerify ..当有人@了你，需要验证口令
func TextVerify(r *Robots, data *modul.ReceiveData) int {
	//thash := wdutil.MD5([]byte(text))
	headlen := len("我是主播")
	if (headlen + 2) >= len(data.Content) {
		textVerify_again("default", r, data)
		return -1
	}
	if res := textVerify_again(data.Content[len(data.Content)-headlen:], r, data); res > 0 {
		return res
	}
	//else if res:=textVerify_again(data.Content[len(data.Content)-(headlen+2):],r,data);res>0 {
	//	return  res
	//}
	requests.SendText(r.Wid, data.FromGroup, "当前指令不识别，请@小助手发送如下内容进行操作：\n我是主播\n开始直播\n结束直播", false)
	wdlog.Debugln(data.Content)
	wdlog.Debugln(headlen, len(data.Content), data.Content[headlen:])
	return -1
}

func textVerify_again(text string, r *Robots, data *modul.ReceiveData) int {
	switch text {
	case "我是主播":
		if r.WorkProgress > 1 {
			requests.SendText(r.Wid, data.FromGroup, "当前状态无法设置主播，请停止直播直播转播录播后设置", false)
			return r.WorkProgress
		}
		//r.CurrentOwner = data.FromUser
		if r.CurrentGroup == "wu" {
			r.CurrentGroup = data.FromGroup
		}
		if r.CurrentGroup == data.FromGroup {
			if _, ok := r.LiveGroupsWcid.Load(r.CurrentGroup); ok {
				r.LiveGroupsWcid.Delete(r.CurrentGroup)
			}
			r.CurrentListWcid.Store(data.FromUser, true)
			r.UpdataRobot_Config()
			requests.SendText(r.Wid, data.FromGroup, "主讲人设置成功", false)
			NewRecordAndInsert(r.ID, r.NickName, data.Content, "机器人被主讲人认证")
		}
		return 1
	case "开始直播":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			if r.WorkProgress > 100 {
				return r.WorkProgress
			}
			r.WorkProgress = 100
			r.UpdataRobot_Config()
			requests.SendText(r.Wid, data.FromGroup, "小助手"+r.NickName+"开始持续为您转播", false)
			return 100
		}
	case "结束直播":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			if r.WorkProgress != 100 {
				return r.WorkProgress
			}
			r.WorkProgress = 1
			r.UpdataRobot_Config()
			requests.SendText(r.Wid, data.FromGroup, "感谢您的使用"+"\n——"+r.NickName, false)
			return 1 //转播结束
		}
	case "开始录播":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			if r.WorkProgress == 100 {
				requests.SendText(r.Wid, data.FromGroup, "当前正在直播，无法进行录播", false)
				return r.WorkProgress
			}
			res := wdutil.RegexpFromStringS(data.Content, `-(?s:(.*?))-`, 1)
			if len(res) < 1 {
				requests.SendText(r.Wid, data.FromGroup, "课程名称设置错误，请按如下格式发送指令设置开始录播：\n@小助手 -我的第一堂课-开始录播", false)
				return -1
			}
			r.Broadcasst = AddBroadcastCourse(uint32(r.ID), res[0][1])
			if r.Broadcasst == nil || r.ID < 1 {
				requests.SendText(r.Wid, data.FromGroup, "课程名称重复，请设置其他名称", false)
				return -1
			}
			r.WorkProgress = 200
			r.UpdataRobot_Config()
			requests.SendText(r.Wid, data.FromGroup, "录播开始", false)
			//requests.SendText(r.Wid,data.FromGroup,r.NickName+" 为您开启录播，请按如下格式，发送指令设置课程名称：\n@小助手 -我的第一堂课-课程名称",false)
			return r.WorkProgress
		}
	case "结束录播":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			if r.WorkProgress != 200 {
				requests.SendText(r.Wid, data.FromGroup, "没有正在进行录播的课程", false)
				return -1
			}
			r.WorkProgress = 1
			r.UpdataRobot_Config()
			requests.SendText(r.Wid, data.FromGroup, r.NickName+" 录播结束，感谢您的使用", false)
			return r.WorkProgress
		}
	case "所有课程":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			//r.WorkProgress = 203
			//requests.SendText(r.Wid,data.FromGroup,r.NickName+" 录播结束，感谢您的使用",false)
			//return r.WorkProgress
		}
	case "开始转播":
		if _, ok := r.CurrentListWcid.Load(data.FromUser); r.CurrentGroup == data.FromGroup && ok {
			if r.WorkProgress == 100 || r.WorkProgress == 200 {
				requests.SendText(r.Wid, data.FromGroup, "当前状态无法转播，请停止直播和录播，然后再进行转播", false)
				return r.WorkProgress
			}
			res := wdutil.RegexpFromStringS(data.Content, `-(?s:(.*?))-`, 1)
			if len(res) < 1 {
				requests.SendText(r.Wid, data.FromGroup, "课程名称错误，请按如下格式发送指令设置开始录播：\n@小助手 -我的第一堂课-开始转播", false)
				return -1
			}
			if wdlog.Error(r.Broadcasst.SelectByCourseName(res[0][1])) {
				requests.SendText(r.Wid, data.FromGroup, "课程："+res[0][1]+" 不存在", false)
				return -1
			}
			if wdlog.Error(r.Broadcasst.SelectByCourseName(res[0][1])) {
				return -1
			}
			if allmsg, n := GetAllMsgBy_CourseId(uint32(r.Broadcasst.ID)); n > 0 {
				go SendBoradcastMsg(r, allmsg)
				r.WorkProgress = 300
			} else {
				return -1
			}
			return r.WorkProgress
		}
	default:
		//requests.SendText(r.Wid,data.FromGroup,"当前指令不识别，请@小助手发送如下内容进行操作：\n为本群开始转播服务\n开启直播\n结束直播",false)
	}
	return -1
}

func SendBoradcastMsg(r *Robots, msgs []BroadcastMsg) {
	for _, v := range msgs {
		time.Sleep(time.Millisecond * 2)
		switch v.MsgType {
		case 1:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendText(r.Wid, wcid, v.Content, false)
				if wdlog.Error(err) {
					return false
				}
				return true
			})
		case 2:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendImage(r.Wid, wcid, v.Content)
				if wdlog.Error(err) {
					return false
				}
				return true
			})
		case 3:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendMV(r.Wid, wcid, v.Content)
				if wdlog.Error(err) {

					return false

				}
				return true
			})
		case 4:
			r.RangeWorkGroup(func(wcid string) bool {
				time.Sleep(time.Millisecond * jiangge)
				err := requests.SendVoice(r.Wid, wcid, v.Content, v.Length)
				if wdlog.Error(err) {

					return false

				}
				return true
			})
		case 5:
		}
	}
	r.WorkProgress = 1
}
